﻿using KPI.Data;
using KPI.Entity;
using KPI.UIBase;
using ScheduleManager.DB;
using ScheduleManager.Helpers;
using ScheduleManager.ViewModels;
using ScheduleManager.Views;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using TYControls;

namespace ScheduleManager
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : TYWindow
    {

        ViewModelScheduleManager vm = new ViewModelScheduleManager();
        private DateTime? start_date;
        private DateTime? end_date;

        public MainWindow()
        {
            InitializeComponent(); InitializeComponent();
            this.DataContext = vm;
            this.Loaded += MainWindow_Loaded;
        }
        private bool hasInit = false;
        List<IntStringData> listDictData = new List<IntStringData>();
        private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= MainWindow_Loaded;
            var rData = await Run(() =>
            {
                return DictDataDBHelper.GetList($"{EnumDictType.shift}");

            });
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                return;
            }
            AppDictData.Update(EnumDictType.shift, rData.data);
            listDictData.Clear();
            rData.data.ForEach(x =>
            {
                listDictData.Add(new IntStringData { Key = x.dict_value, Value = x.dict_label });
            });

            BtnClick_Search(null, null);
            hasInit = true;
        }

        private void BtnClick_Search(object sender, RoutedEventArgs e)
        {
            pager.CurrentPage = 1;
            pager_CurrentPageChanged(null, null);
        }

        public DateTime GetMonday(DateTime dateTime)
        {
            int delta = ((int)dateTime.DayOfWeek + 6) % 7; // 计算需要减去的天数
            DateTime monday = dateTime.AddDays(-delta); // 减去天数得到周一日期
            return monday;
        }
        private async void pager_CurrentPageChanged(object sender, Panuon.WPF.SelectedValueChangedRoutedEventArgs<int> e)
        {
            if (IsLoaded == false)
                return;
            int pageIndex = pager.CurrentPage;
            ScheduleVO queryDto = new ScheduleVO()
            {
                user_name = vm.Name,
                schedule = new Tbl_Schedule
                {

                    start_date = GetMonday(vm.StartTime == null ? DateTime.Now : vm.StartTime.Value)
                }
            };
            vm.StartTime = queryDto.schedule.start_date;
            queryDto.schedule.end_date = queryDto.schedule.start_date.Value.AddDays(7);

            this.start_date = queryDto.schedule.start_date;
            this.end_date = queryDto.schedule.end_date;
            vm.ListSchedule.Clear();
            var rData = await Run(() =>
            {
                return ScheduleDBHelper.GetList(new PageInfo(pageIndex, 20), queryDto);
            });
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                return;
            }
            pager.MaxPage = rData.page.PageCount();
            foreach (var item in rData.data)
            {
                ScheduleModel model = UIDataHelper.DataAsUI(item, listDictData);
                model.Index = vm.ListSchedule.Count + 1;
                vm.ListSchedule.Add(model);
            }
        }

        //private async void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    if (hasInit == false)
        //        return;
        //    var model = (sender as ComboBox).DataContext as ScheduleModel;
        //    if (model == null)
        //    {
        //        return;
        //    }
        //    Tbl_Schedule schedule = new Tbl_Schedule()
        //    {
        //        user_id = model.data.user_id,
        //        start_date = this.start_date,
        //        end_date = this.end_date,
        //        schedule_id = model.data.schedule_id,
        //        shift1_key = model.Shift1_key.Key,
        //        shift2_key = model.Shift2_key.Key,
        //        shift3_key = model.Shift3_key.Key,
        //        shift4_key = model.Shift4_key.Key,
        //        shift5_key = model.Shift5_key.Key,
        //        shift6_key = model.Shift6_key.Key,
        //        shift7_key = model.Shift7_key.Key,
        //    };
        //    var rData = await Run(() =>
        //     {
        //         return ScheduleApi.Edit(schedule);
        //     });
        //    if (rData.code != 0)
        //    {
        //        this.ShowMsg(rData.msg);
        //        return;
        //    }
        //    ScheduleModel newModel = UIDataHelper.DataAsUI(rData.data, vm.ListShift);
        //    newModel.Index = model.Index;
        //    newModel.UserName = model.UserName;
        //    int index = vm.ListSchedule.IndexOf(model);
        //    vm.ListSchedule[index] = newModel;
        //}

        private void BtnClick_Search_PreWeek(object sender, RoutedEventArgs e)
        {
            vm.StartTime = vm.StartTime.Value.AddDays(-7);
            pager_CurrentPageChanged(null, null);
        }


        private void BtnClick_Search_NextWeek(object sender, RoutedEventArgs e)
        {
            vm.StartTime = vm.StartTime.Value.AddDays(7);
            pager_CurrentPageChanged(null, null);
        }

        private void DataGrid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (vm.SelectedSchedule == null)
            {
                return;
            }
            var data = vm.SelectedSchedule.data;
            if (data == null)
            {
                data = new ScheduleVO();
            }
            if (data.schedule.start_date == null)
            {
                data.schedule.start_date = this.start_date;
                data.schedule.end_date = this.end_date;
            }
            ViewEditSchedule view = new ViewEditSchedule(data);
            if (view.ShowDialog() != true)
                return;
            listDictData.Clear();
            var dictShift = AppDictData.GetList(EnumDictType.shift);
            foreach (var item in dictShift)
            {
                IntStringData intString = new IntStringData() { Key = item.Key, Value = item.Value };
                listDictData.Add(intString);
            }
            BtnClick_Search(null, null);
        }

        // 辅助方法，用于查找可视树中的父元素
        private T FindVisualParent<T>(DependencyObject obj) where T : DependencyObject
        {
            while (obj != null)
            {
                if (obj is T)
                {
                    return (T)obj;
                }
                obj = VisualTreeHelper.GetParent(obj);
            }
            return null;
        }
    }
}
